﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using System.IO.Ports;
using System.Threading;

namespace Lamex.mSchedule.UI
{
    public partial class frm_SCH_ScanFollowUp : frmBaseChild
    {
        SerialPort serialPort1 = new SerialPort();
        SerialPort serialPort2 = new SerialPort();
        SerialPort serialPort3 = new SerialPort();
        SerialPort serialPort4 = new SerialPort();
        SerialPort serialPort5 = new SerialPort();
        SerialPort serialPort6 = new SerialPort();
        SerialPort serialPort7= new SerialPort();
        SerialPort serialPort8= new SerialPort();
        string COM1 = "";
        string COM2 = "";
        string COM3 = "";
        string COM4 = "";
        string COM5 = "";
        string COM6 = "";
        string COM7 = "";
        string COM8 = "";
        public int iBeForComSum = 0;
        public int iAfterComSum = 0;
        Thread threadReceiveSub1 = null;
        Thread threadReceiveSub2 = null;
        Thread threadReceiveSub3 = null;
        Thread threadReceiveSub4 = null;
        Thread threadReceiveSub5 = null;
        Thread threadReceiveSub6 = null;
        Thread threadReceiveSub7 = null;
        Thread threadReceiveSub8 = null;

        System.Timers.Timer time1 = null;
        System.Timers.Timer time2 = null;
        System.Timers.Timer time3 = null;
        System.Timers.Timer time4 = null;
        System.Timers.Timer time5 = null;
        System.Timers.Timer time6 = null;
        System.Timers.Timer time7 = null;
        System.Timers.Timer time8 = null;

        public frm_SCH_ScanFollowUp()
        {
            InitializeComponent();
            this.Load += new EventHandler(frm_SCH_ScanFollowUp_load);
            this.FormClosing += new FormClosingEventHandler(frm_SCH_ScanFollowUp_FormClosing);
            
        }
        private void frm_SCH_ScanFollowUp_load(object sender, EventArgs e)
        {
            InitCom();
            //CheckRunComNum();--
        }
        private string[] GetRunCom()
        {
            string[] str = SerialPort.GetPortNames();
            return str;
        }
       private void InitCom()
        {
            string[] str = GetRunCom();
            iBeForComSum = str.Count();
            if (str == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
                return;
            }
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\ComSetting.ini");
            COM1 = ini.IniReadValue("COM Configuration", "COM1");
            COM2 = ini.IniReadValue("COM Configuration", "COM2");
            COM3 = ini.IniReadValue("COM Configuration", "COM3");
            COM4 = ini.IniReadValue("COM Configuration", "COM4");
            COM5 = ini.IniReadValue("COM Configuration", "COM5");
            COM6 = ini.IniReadValue("COM Configuration", "COM6");
            COM7 = ini.IniReadValue("COM Configuration", "COM7");
            COM8 = ini.IniReadValue("COM Configuration", "COM8");
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == COM1)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(s, serialPort1);
                }
                else if (s == COM2)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(s, serialPort2);
                }
                else if (s == COM3)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(s, serialPort3);
                }
                else if (s == COM4)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(s, serialPort4);
                }
                else if (s == COM5)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(s, serialPort5);
                }
                else if (s == COM6)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(s, serialPort6);
                }
                else if (s == COM7)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(s, serialPort7);
                }
                else if (s == COM8)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(s, serialPort8);
                }

                //System.Threading.Thread.Sleep(1000);

            }

            alterTime();
        }

        private void InitSingleCom(string PortName)
        {
            string[] str = GetRunCom();
           
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == PortName)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort1);
                }
                else if (s == PortName)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort2);
                }
                else if (s == PortName)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort3);
                }
                else if (s == PortName)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort4);
                }
                else if (s == PortName)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort5);
                }
                else if (s == PortName)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort6);
                }
                else if (s == PortName)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort7);
                }
                else if (s == PortName)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort8);
                }

                System.Threading.Thread.Sleep(1000);

            }
        }
        /// <summary>
        /// 实例化串行端口资源
        /// </summary>
        private void InstanceSerialPort(string comName, SerialPort serialPort)
        {


            try
            {
                //实例化串行端口
                //SerialPort serialPort = new SerialPort();
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = comName;
                //波特率
                serialPort.BaudRate = 9600;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 8;
                //忽略null字节
                serialPort.DiscardNull = true;

                //接收事件
                serialPort.DataReceived += serialPort_DataReceived;
                //开启串口
                serialPort.Open();
                //alterTime();
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            try
            {
                ReceiveData(serialPort);
                //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(ReceiveData));
                //threadReceiveSub.IsBackground = true;
                //threadReceiveSub.Start(serialPort);
                //Thread.Sleep(100);
                //threadReceiveSub.Abort();

                //开启接收数据线程
                //if(serialPort.PortName==COM1)
                //{
                //    threadReceiveSub1 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub1.IsBackground = true;
                //    threadReceiveSub1.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM2)
                //{
                //    threadReceiveSub2 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub2.IsBackground = true;
                //    threadReceiveSub2.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM3)
                //{
                //    threadReceiveSub3 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub3.IsBackground = true;
                //    threadReceiveSub3.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM4)
                //{
                //    threadReceiveSub4 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub4.IsBackground = true;
                //    threadReceiveSub4.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM5)
                //{
                //    threadReceiveSub5 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub5.IsBackground = true;
                //    threadReceiveSub5.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM6)
                //{
                //    threadReceiveSub6 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub6.IsBackground = true;
                //    threadReceiveSub6.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM7)
                //{
                //    threadReceiveSub7 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub7.IsBackground = true;
                //    threadReceiveSub7.Start(serialPort);
                //}
                //else if (serialPort.PortName == COM3)
                //{
                //    threadReceiveSub8 = new Thread(new ParameterizedThreadStart(ReceiveData));
                //    threadReceiveSub8.IsBackground = true;
                //    threadReceiveSub8.Start(serialPort);
                //}
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message, serialPort.PortName);
            }
        }

        private void ReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            try
            {


                //防止数据接收不完整 线程sleep(100)
                System.Threading.Thread.Sleep(100);

                string str = serialPort.ReadExisting();

                if (str == string.Empty)
                {
                    return;
                }
                else
                {
                    SetMessage(str, serialPort.PortName);
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message, serialPort.PortName);
            }
        }
        
        /// <summary>
        /// 添加记录
        /// </summary>
        /// <param name="msg"></param>
        private void SetMessage(string msg, string portName)
        {
            
            if (portName == COM1)
            {
                Invoke(new Action(() => { txtCom1.Text= COM1+":" + msg + "\r\n"; txtBarcode.Text = COM1 + ":"  + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM1 + ":" + msg + "\r\n");  }));
            }
            else if (portName == COM2)
            {
                Invoke(new Action(() => { txtCom2.Text = COM2 + ":" + msg + "\r\n"; txtBarcode.Text = COM2 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM2 + ":" + msg + "\r\n"); }));
            }
            else if (portName == COM3)
            {
                Invoke(new Action(() => { txtCom3.Text = COM3 + ":" + msg + "\r\n"; txtBarcode.Text = COM3 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM3 + ":" +msg + "\r\n"); }));
            }
            else if (portName == COM4)
            {
                Invoke(new Action(() => { txtCom4.Text = COM4 + ":" + msg + "\r\n"; txtBarcode.Text = COM4 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM4 + ":" + msg + "\r\n"); }));
            }
            else if (portName == COM5)
            {
                Invoke(new Action(() => { txtCom5.Text = COM5 + ":" + msg + "\r\n"; txtBarcode.Text = COM5 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM5 + ":" + msg + "\r\n"); }));
            }
            else if (portName == COM6)
            {
                Invoke(new Action(() => { txtCom6.Text = COM6 + ":" + msg + "\r\n"; txtBarcode.Text = COM6 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM6 + ":" + msg + "\r\n"); }));
            }
            else if (portName == COM7)
            {
                Invoke(new Action(() => { txtCom7.Text = COM7 + ":" + msg + "\r\n"; txtBarcode.Text = COM7 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM7 + ":" + msg + "\r\n"); }));
            }
            else if (portName == COM8)
            {
                Invoke(new Action(() => { txtCom3.Text = COM8 + ":" + msg + "\r\n"; txtBarcode.Text = COM8 + ":" + msg + "\r\n"; }));
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(COM8 + ":" + msg + "\r\n"); }));
            }


        }

        private void alterTime()
        {
            time1 = new System.Timers.Timer();
            time1.Enabled = true;
            time1.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            time1.Start();
            time1.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);

            //if (PortName==COM1)
            //{
            //    time1 = new System.Timers.Timer();
            //    time1.Enabled = true;
            //    time1.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time1.Start();
            //    time1.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //else if (PortName == COM2)
            //{
            //    time2 = new System.Timers.Timer();
            //    time2.Enabled = true;
            //    time2.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time2.Start();
            //    time2.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //else if (PortName == COM3)
            //{
            //     time3 = new System.Timers.Timer();
            //    time3.Enabled = true;
            //    time3.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time3.Start();
            //    time3.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //if (PortName == COM4)
            //{
            //    time4 = new System.Timers.Timer();
            //    time4.Enabled = true;
            //    time4.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time4.Start();
            //    time4.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //if (PortName == COM5)
            //{
            //    time5 = new System.Timers.Timer();
            //    time5.Enabled = true;
            //    time5.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time5.Start();
            //    time5.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //if (PortName == COM6)
            //{
            //    time6 = new System.Timers.Timer();
            //    time6.Enabled = true;
            //    time6.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time6.Start();
            //    time6.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //if (PortName == COM7)
            //{
            //    time7 = new System.Timers.Timer();
            //    time7.Enabled = true;
            //    time7.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time7.Start();
            //    time7.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}
            //if (PortName == COM8)
            //{
            //    time8 = new System.Timers.Timer();
            //    time8.Enabled = true;
            //    time8.Interval = 5000 * 5; //执行间隔时间,单位为毫秒; 这里实际间隔为5分秒 
            //    time8.Start();
            //    time8.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //}


        }
       
        private void Timer_TimesUp1(object sender, System.Timers.ElapsedEventArgs e)
        {
            string[] str = GetRunCom();
            iAfterComSum = str.Count();
            if(iAfterComSum!=iBeForComSum)
            {
                Timer_TimesUp(null,null);
                iBeForComSum = iAfterComSum;
            }
        }
         private void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (COM1 == serialPort1.PortName)
            {
                if (serialPort1.IsOpen != true)
                {
                    serialPort1.Close();
                    InitSingleCom(serialPort1.PortName);
                    //InstanceSerialPort(serialPort1.PortName, serialPort1);
                }
                    
            }
            if (COM2 == serialPort2.PortName)
            {
                if (serialPort2.IsOpen != true)
                {
                    serialPort2.Close();
                    InitSingleCom(serialPort2.PortName);
                    //InstanceSerialPort(serialPort2.PortName, serialPort2);
                }
                    
            }
            if (COM3 == serialPort3.PortName)
            {
                if (serialPort3.IsOpen != true)
                {
                    serialPort3.Close();
                    InitSingleCom(serialPort3.PortName);
                    //InstanceSerialPort(serialPort3.PortName, serialPort3);
                }
                    
            }
            if (COM4 == serialPort4.PortName)
            {
                if (serialPort4.IsOpen != true)
                {
                    serialPort4.Close();
                    InitSingleCom(serialPort4.PortName);
                    //InstanceSerialPort(serialPort4.PortName, serialPort4);
                }
                    
            }
            if (COM5 == serialPort5.PortName)
            {
                if (serialPort5.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort5.PortName);
                    //InstanceSerialPort(serialPort5.PortName, serialPort5);
                }
            }
            if (COM6 == serialPort6.PortName)
            {
                if (serialPort6.IsOpen != true)
                {
                    serialPort6.Close();
                    InitSingleCom(serialPort6.PortName);
                    //InstanceSerialPort(serialPort6.PortName, serialPort6);
                }
            }
            if (COM7 == serialPort7.PortName)
            {
                if (serialPort7.IsOpen != true)
                {
                    serialPort7.Close();
                    InitSingleCom(serialPort7.PortName);
                    //InstanceSerialPort(serialPort7.PortName, serialPort7);
                }
            }
            if (COM8 == serialPort8.PortName)
            {
                if (serialPort8.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort8.PortName);
                    //InstanceSerialPort(serialPort8.PortName, serialPort8);
                }
            }

        }

        private void frm_SCH_ScanFollowUp_FormClosing(object sender, FormClosingEventArgs e)
        {
            //threadReceiveSub.Abort();
            //threadReceiveSub1.Abort();

            time1.Dispose();
            time1.Close();
            serialPort1.Dispose();
            serialPort2.Dispose();
            serialPort3.Dispose();
            serialPort4.Dispose();
            serialPort5.Dispose();
            serialPort6.Dispose();
            serialPort7.Dispose();
            serialPort8.Dispose();
            serialPort1.Close();
            serialPort2.Close();
            serialPort3.Close();
            serialPort4.Close();
            serialPort5.Close();
            serialPort6.Close();
            serialPort7.Close();
            serialPort8.Close();
            

        }
    }
}